<?php 
/* 
 * This file is part of TCDB. 
 * 
 * Copyright (C) 2000-2009 
 * Technology Consultant Corps 
 * Grinnell College 
 * Grinnell, IA, 50112 
 * tc@grinnell.edu 
 * 
 * TCDB is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * TCDB is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with TCDB. If not, see <http://www.gnu.org/licenses/>. 
 * 
 
 ============================================================================= 
 
 * add_users.php -- Allows an admin to add a number of new users by entering 
 *		   their usernames; then, the script pulls info from the DB,
 *                 notifies the admin of accounts that were created and those
 *                 that the script failed to create, then sends an e-mail to 
 *                 the users notifying them that an account was created
 *
 *		   It is important to note that a number of default values
 *		   are set here; for instance, all added users begin with
 *		   a rank_id of 1 (a Trainee). We found that having an
 *		   interface that made it easy to add a batch of users with
 *		   Trainee defaults was better than the old method of 
 *		   having to set those defaults for EVERY user. All of this
 *                 information can changed through edit_users.php, anyway
 * 
 * Author: Dylan J. Sather
 * Created: 2009-06-30 
 * Last edited: 2009-07-21
 *
 * Thanks to Avram Lyon for his work on add_user.php since March, 2004
 */ 
 
$page_title = "add_users.php"; 

require('init.php'); 
require('require_login.php'); 
require('require_admin.php'); 
include('header.php'); 

?>

<div class="content_box"> <!-- CONTENT div -->

<?php

// If we don't have any usernames stored in the $_POST array, we're creating users
if (!isset($_POST["usernames"])) {
    echo "<h3>Please enter the new users' usernames, separated by <span class='underline'>commas</span></h3>
    <p>All user info will be pulled from Pweb or auto-generated; an e-mail will be sent to the user<br />
       notifying him or her that an account was created</p>
    <form method='post' action='add_users.php'>
      <p>
        <input type='text' name='usernames' size='30' /><br />
        <input type='submit' value='Create Users' />
      </p>
    </form>";
}

// Otherwise, we have a set of users and we have to create accounts for them
else {
    // Take data from the usernames string and 'explode' into array data
    $usernames = explode(",", $_POST["usernames"]);
    
    // Initialize important variables and arrays
    $FETCH_URL = "https://pioneerweb.grinnell.edu/scripts-docs/roster/feedster.asp?usr=";
    $CURRENT_DATE = date('Y-m-d');
    $pweb_array = array("first_name", "last_name", "e-mail", "box", "class",
		  "phone", "OCphone", "major", "concentration");
    $tcdb_array = array("first_name", "last_name", "email", "box_num", "class", 
		  "campus_phone", "campus_phone", "major", "concentration");
    $created_accounts = array();
    $invalid_users = array();
    $hire_date = date('Y-m-d');
    $last_updated = $hire_date;

    /* We need to initialize each of the variables in $tcdb_array; if we don't, 
       we'll get an error when trying to update information in the DB, since
       the variable will not yet be defined (this will only occur if the data we
       pull from Pweb is 'empty' */
    foreach ($tcdb_array as $value) {
	${$value} = NULL;
    }

    // For each user in the $usernames array...
    foreach ($usernames as $user) {
	
	/* Remove any whitespace that would have occured before or after a comma from
	   the string of usernames (otherwise the URI from which we pull may be 
	   malformed, causing us to fetch invalid data) */

	$user = trim($user);

	// Load and parse XML
	$xmldoc = simplexml_load_file($FETCH_URL . $user);

	// If we're able to fetch the XML doc...
	if ($xmldoc) {

	    /* For each element in $pweb_array, we need to update the corresponding element in $tcdb_array;
	       hence, we iterate through the array and use indices to determine where we're at. Using
	       foreach() simply wouldn't work for what we want to do */

	    for ($i = 0; $i < count($pweb_array); $i++) {
		$data = $xmldoc->xpath("//$pweb_array[$i]");
		if (!empty($data[0])) {

		    // If we pull data for an Invalid user, we need to add the name to the $invalid_users array
		    if ($data[0] == 'Invalid') {
			if (!in_array($user, $invalid_users)) {
			    $invalid_users[] = "$user";
			}
		    }

		    // Otherwise, the user is a valid user
		    else {
			// Save $data[0] in corresponding $tcdb_array variables
			${$tcdb_array[$i]} = $data[0];
		    }
		}
	    }
	  
	    // If our user is valid, INSERT his info into the DB 
	    if (!in_array($user, $invalid_users)) {
		
		// Create a random, six-character password
		$password = '';
		for ($i = 0; $i < 6; $i++) {
		    $password .= chr(round(rand(65,90)));
		}

		// INSERT info into DB	
		$query = sprintf("INSERT INTO users
				  (username, password, first_name, last_name,
				   email, campus_phone, box_num, hire_date,
				   class, major, concentration, last_updated)
				  VALUES
				  ('%s','%s','%s','%s',
				   '%s','%s','%s','%s',
				   '%s','%s','%s','%s')",
			      mysqli_real_escape_string($mysqli, $user),
			      mysqli_real_escape_string($mysqli, sha1($password)),
			      mysqli_real_escape_string($mysqli, $first_name),
			      mysqli_real_escape_string($mysqli, $last_name),
			      mysqli_real_escape_string($mysqli, $email),
			      mysqli_real_escape_string($mysqli, $campus_phone),
			      mysqli_real_escape_string($mysqli, $box_num),
			      mysqli_real_escape_string($mysqli, $hire_date),
			      mysqli_real_escape_string($mysqli, $class),
			      mysqli_real_escape_string($mysqli, $major),
			      mysqli_real_escape_string($mysqli, $concentration),
			      mysqli_real_escape_string($mysqli, $last_updated));
		
		$result = $mysqli->query($query);

		// If we didn't get any error from the INSERT, add the user to the $created_accounts array
		if (!$mysqli->error) {
		    if (!in_array($user, $created_accounts)) {
			$created_accounts[] = $user;
		    }
		}
		
		// Otherwise, we should add them to the $invalid_users array
		else {
		    $invalid_users[] = $user;
		}

		// Finally, e-mail the user, letting him know his account was created
		$to = 'satherdy@grinnell.edu';
		$subject = $config["system_title"] . ' account created';
		$msg = 'A TC Corps account was created for you at http://' . $_SERVER['SERVER_NAME'] . "\n" . 
		       "Please log on, update your Directory information, and change your password\n\n" .
		       "Username: $user\n" .
		       "Password: $password\n";
		$headers = 'From: new.account@tcdb.grinnell.edu' . "\r\n" .
			   'Reply-To: ' . $config["system_email"] . "\r\n" .
			   'Cc: ' . $config["system_email"] . "\r\n";

		mail($to, $subject, $msg, $headers);
	    }
	}

	/* Otherwise, we're not able to fetch the XML and we should add
	   the name to the $invalid_users array */
	else {
	    if (!in_array($user, $invalid_users)) {
		$invalid_users[] = "$user";
	    }
	}
    }

    // Print a confirmation that users were created
    echo "<h3>Accounts for the following users were created successfully:</h3>";

    foreach ($created_accounts as $user) {
	echo "$user<br />";
    }

    // And also list the accounts that were not successfully created
    echo "<h3>... but the script couldn't pull info on these users:</h3>";

    foreach ($invalid_users as $user) {
	echo "$user<br />";
    }
}

?>

</div> <!-- End CONTENT div -->

<?php

include('footer.php'); 

?> 
